import json

from flask import request, Blueprint, g

from api.decorators import login_required, cache
from api.slider import get_json_response
from exts import db
from models import BookSelf

book_self = Blueprint('book_self', __name__)


@book_self.route('/bookSelf/add', methods=['POST'])
@login_required
def add():
    login_user = g.user
    if request.content_length > 0:
        request_obj = json.loads(request.data, encoding='UTF-8')
        book_self_obj = BookSelf()
        book_self_obj.bookId = request_obj.get('bookId', '')
        book_self_obj.user_id = login_user.id
        temp = BookSelf.query.filter(
            BookSelf.user_id == login_user.id and BookSelf.bookId == book_self_obj.bookId).first()
        if temp:
            book_self_obj = temp
        book_self_obj.author = request_obj.get('author', '')
        book_self_obj.sourceId = request_obj.get('sourceId', '')
        book_self_obj.cover = request_obj.get('cover', '')
        book_self_obj.title = request_obj.get('title', '')
        book_self_obj.isInShelf = request_obj.get('isInShelf')
        book_self_obj.lastChapter = request_obj.get('lastChapter')
        book_self_obj.readChapter = request_obj.get('readChapter')
        book_self_obj.sort = request_obj.get('sort')
        book_self_obj.updated = request_obj.get('updated')
        db.session.add(book_self_obj)
        db.session.commit()
    response_dic = {
        'err': False
    }
    return get_json_response(response_dic, request)


@book_self.route('/bookSelf/remove', methods=['POST'])
@login_required
def remove():
    login_user = g.user
    if request.content_length > 0:
        request_obj = json.loads(request.data, encoding='UTF-8')
        book_id = request_obj.get('bookId', '')
        temp = BookSelf.query.filter(BookSelf.user == login_user and BookSelf.bookId == book_id).delete()
        print(temp)
    response_dic = {
        'err': False
    }
    return get_json_response(response_dic, request)


@book_self.route('/bookSelf/all', methods=['GET'])
@login_required
def get_user_book_self():
    login_user = g.user
    book_selves = login_user.book_selves
    book_selves_dict = {}
    for item in book_selves:
        item_dict = item.__dict__
        del item_dict['_sa_instance_state']
        del item_dict['user_id']
        book_selves_dict[item.bookId] = item_dict
    response_dic = {
        'err': False,
        'bookSelves': book_selves_dict
    }
    return get_json_response(response_dic, request)
